#include "orangepch.h"
#include "Scene.h"
#include "Component.h"
#include "Renderer/Renderer2D.h"
#include "Entity.h"
namespace Orange {

	Scene::Scene()
	{
		entt::entity entity = m_Register.create();
	}

	Scene::~Scene()
	{

	}

	void Scene::OnUpdate(Time detalTime)
	{
		
		/// update script
		m_Register.view<NativeScriptComponent>().each([=](auto entity, NativeScriptComponent& script) {

			if (!script.Instance) {
		
				script.Instance = script.OnCreateEntity();

				script.Instance->m_entity = Entity{ entity , this };

				script.Instance->OnCreate();

			}
				script.Instance->OnUpdate(detalTime);
			});

		
	
		auto cameraGroup = m_Register.view<TransformComponent, CameraComponent>();
		 Camera* primaryCamera = nullptr;
		 glm::mat4 cameraTransform  ;

		for (const auto entity : cameraGroup) {
	
			auto [transform, camera] = cameraGroup.get<TransformComponent, CameraComponent>(entity);

			if (camera.Primary) {
				primaryCamera = &camera.camera;
				cameraTransform = transform.GetTransform();
			}
			
		}

		if (primaryCamera) {
			Renderer2D::StartScene(primaryCamera->GetPrejectMatrix(), cameraTransform);

			auto group = m_Register.group<TransformComponent>(entt::get<SpriteRendererComponent>);
			
			for (auto entity : group) {

				auto [transform, sprite] = group.get<TransformComponent, SpriteRendererComponent>(entity);
			
				Renderer2D::DrawQuad(transform.GetTransform(), sprite.Color);
			}


			Renderer2D::EndScene();
		}

		
	}

	void Scene::OnSetViewportSize(uint32_t width, uint32_t height) {
		m_ViewportWidth = width;
		m_ViewportHeight = height;

		auto view = m_Register.view<CameraComponent>();

		for (auto entity : view) {

			auto& camera = view.get<CameraComponent>(entity);

			if (!camera.FixAspecRadius) {
				
				camera.camera.SetViewportSize(width, height);
			}

		}

	};

	Entity Scene::CreateEntity(const std::string& name)
	{

		Entity entity = { m_Register.create(), this };
		entity.AddComponent<TransformComponent>();
		auto& tag = entity.AddComponent<TagComponent>();
		tag.tag = name.empty() ? "Entity" : name;
		return entity;
	}

	void Scene::DestroyEntity(Entity entity)
	{
		m_Register.destroy(entity);
	}





}
